package 笔记.多线程;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author CHL
 * @ClassName: Semaphore
 * @Description: 信号量
 * @date 2023/11/3 17:28
 * @Version 1.0
 */
public class SemaphoreDemo {
    /*
     * 多个共享资源互斥的使用！并发限流，控制最大的线程数！
     * 订单抢购应用场景
     * */
    public static void main(String[] args) {

        // 线程数量：停车位! 用来限流！
        Semaphore semaphore = new Semaphore(3);
        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                //acquire() 得到
                //release() 释放
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到车位！");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName()+"离开车位！");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }

            }, String.valueOf(i)).start();

        }
    }

}
